//index.js
//获取应用实例
let Axios = require('../../../common/js/ajax.js');
let Mtils = require('../../../common/js/Mtils.min.js');
var util = require('../../../common/utils/util.js'); //转换时间插件
var webim = require('../../../common/utils/webim_wx.js');
var webimhandler = require('../../../common/utils/webim_handler.js');
var tls = require('../../../common/utils/tls.js');
Mtils = Mtils.Mtils
var app = getApp()
global.webim = webim;
var selSess = null;
var selType = webim.SESSION_TYPE.C2C;
var selToID, selSessHeadUrl;
var loginInfo = {
	'sdkAppID': app.data.Config.sdkappid, //用户所属应用id,必填
	'appIDAt3rd': app.data.Config.sdkappid, //用户所属应用id，必填
	'accountType': app.data.Config.accountType, //用户所属应用帐号类型，必填
	'identifier': app.globalData.identifier, //当前用户ID,必须是否字符串类型，选填
	'identifierNick': app.globalData.identifierNick, //当前用户昵称，选填
	'userSig': app.globalData.userSig, //当前用户身份凭证，必须是字符串类型，选填
	'icon': app.globalData.avatarUrl,
	'name': app.globalData.nickName,
	'member_icon': '',
	'member_name': ''
};
Page({
	data: {
		motto: 'Hello World',
		userInfo: {},
		msgs: [],
		Identifier: null,
		UserSig: null,
		msgContent: "",
		id: 0,
		scrollTop: 0,
		isIpx: app.globalData.isIpx ? true : false
	},
	onLoad: function(e) {
		var that = this;
		that.setData({
			id: e.id,
		})
		//调用应用实例的方法获取全局数据
		this.uid = app.globalData.uid || ''
		this.Md5 = Mtils.security.hex_md5(this.uid) + app.globalData.secret;
		this.Md5 = Mtils.security.hex_md5(this.Md5);
		this.timesp = Mtils.now();
		let user = wx.getStorageSync('userInfo') || {}
		this.initIM(user);							
	},
	onReady: function() {
		wx.setNavigationBarTitle({
			title: '聊天室'
		})
	},
		onHide() {
		console.log('onHide')
		//this.quitClick()
	},
	onUnload() {
		//this.quitClick()
		console.log('onUnload')
	},
	clearInput: function() {
		this.setData({
			msgContent: ""
		})
	},
	bindConfirm: function(e) {
		var that = this;
		var content = e.detail.value;
		if (!content.replace(/^\s*|\s*$/g, '')) return;
		webimhandler.onSendMsg(content, function() {
			that.clearInput();
		})
	},
	bindinput: function(e) {
		var that = this;
		var content = e.detail.value;
		this.setData({
			msgContent: content
		})
	},
	bindTap: function() {
		var that = this
		var msg = this.data.msgContent;
		that.sendGroupLoveMsg(msg);
	},
	receiveMsgs: function(data) {
		var that = this
		var msgs = this.data.msgs || [];
		msgs.push(data);
		//最多展示10条信息
		if (msgs.length > 10) {
			msgs.splice(0, msgs.length - 10)
		}
		this.setData({
			msgs: msgs
		}, () => {
			that.clearInput()
			that.pageScrollToBottom()
		})
	},
	initIM: function(userInfo) {
		loginInfo = {
			'sdkAppID':1400178898, //用户所属应用id,必填
			'appIDAt3rd': 1400178898, //用户所属应用id，必填
			'accountType': app.data.Config.accountType, //用户所属应用帐号类型，必填
			'identifier': app.globalData.identifier, //当前用户ID,必须是否字符串类型，选填
			'identifierNick': app.globalData.identifierNick, //当前用户昵称，选填
			'userSig': app.globalData.userSig, //当前用户身份凭证，必须是字符串类型，选填
			'icon': app.globalData.avatarUrl,
			'name': app.globalData.nickName,
			'member_icon': '',
			'member_name': ''
		};
		var _this = this;
		wx.showLoading({
			mask:true
		})
		selToID = _this.data.id; //会话列表不设置对方私聊账号	
		webimhandler.init({ //初始化的方法
			accountMode: app.data.Config.accountMode,
			accountType: app.data.Config.accountType,
			sdkAppID: 1400178898,
			selType: webim.SESSION_TYPE.C2C, //私聊
			id: selToID, //如果是经纪人，则填agent_member_id ,如果是普通用户则填经纪人id
			name: app.globalData.nickName,
			icon: app.globalData.avatarUrl,
			that: _this
		});
		if (webim.checkLogin()) { //检查是否登录返回true和false,不登录则重新登录
			console.log('已登录')
			var id = _this.data.id.split(' ')
			_this.quitClick(function(){
				_this.sdkLogin(_this, app, selToID, function() {
					var id = _this.data.id.split(' ')
					_this.getAvatar(id)
				});
			})			
		} else {
			console.log('登录成功')
			_this.quitClick(function(){
				_this.sdkLogin(_this, app, selToID, function() {
					var id = _this.data.id.split(' ')
					_this.getAvatar(id)
				});
			})
		}
	},
	getLastC2CHistoryMsgs: function(selToID, reqMsgCount, cbOk, cbError) {
		var that = this
		if (selType == webim.SESSION_TYPE.GROUP) {
			alert('当前的聊天类型为群聊天，不能进行拉取好友历史消息操作');
			return;
		}
		var lastMsgTime = 0; //第一次拉取好友历史消息时，必须传 0
		var msgKey = '';
		var options = {
			'Peer_Account': selToID, //好友帐号
			'MaxCnt': reqMsgCount, //拉取消息条数
			'LastMsgTime': lastMsgTime, //最近的消息时间，即从这个时间点向前拉取历史消息
			'MsgKey': msgKey
		};
		webim.getC2CHistoryMsgs(
			options,
			function(resp) {
				var complete = resp.Complete; //是否还有历史消息可以拉取，1-表示没有，0-表示有
				var retMsgCount = resp.MsgCount; //返回的消息条数，小于或等于请求的消息条数，小于的时候，说明没有历史消息可拉取了
				if (resp.MsgList.length == 0) {
					webim.Log.error("没有历史消息了:data=" + JSON.stringify(options));
					return;
				}
				options.LastMsgTime = resp.LastMsgTime
				options.MsgKey = resp.MsgKey
				var msgList = resp.MsgList;
				var tempArr = []
				for (var j in msgList) { //遍历新消息
					var msg = msgList[j];
					if (msg.getSession().id() == selToID) { //为当前聊天对象的消息
						selSess = msg.getSession();
					}
					webim.setAutoRead(selSess, true, true)
					var contentHtml = that.showMsg(msg)
					tempArr.push(contentHtml)
				}
				console.log(tempArr)
				that.setData({
					msgs: tempArr
				}, () => {
					wx.hideLoading()
					that.clearInput()
					that.pageScrollToBottom()
				})
			},
			function(resp){
				console.log(resp)
			}
		);
	},
	pageScrollToBottom: function() {
		var that = this;
		wx.createSelectorQuery().select('#j_page').boundingClientRect(function(rect) {
			// 使页面滚动到底部
			that.setData({
				scrollTop: rect.bottom
			})
		}).exec()
	},
	sendGroupLoveMsg: function(msgtext) {
		var that = this;
// 		that.setProfilePortrait({
// 			'ProfileItem': [{
// 				"Tag": "Tag_Profile_IM_Nick",
// 				"Value": 'cs'
// 			}]
// 		}, function() {})
// 		if (!loginInfo.identifier) { //未登录
// 			if (accountMode == 1) { //托管模式
// 				//将account_type保存到cookie中,有效期是1天
// 				//调用tls登录服务
// 				tlsLogin();
// 			} else { //独立模式
// 				console.error('请填写帐号和票据');
// 			}
// 			return;
// 		}
		if (!selSess) {
			selSess = new webim.Session(selType, selToID, selToID, selSessHeadUrl, Math.round(new Date().getTime() / 1000));
		}
		var isSend = true; //是否为自己发送
		var seq = -1; //消息序列，-1表示sdk自动生成，用于去重
		var random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
		var msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳	
		var subType = webim.GROUP_MSG_SUB_TYPE.LOVEMSG;
		var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, loginInfo.identifier, subType, loginInfo.identifierNick);
		var msgtosend = msgtext;
		var text_obj = new webim.Msg.Elem.Text(msgtosend);
		msg.addText(text_obj);
		webim.sendMsg(msg, function(resp) {
			if (selType == webim.SESSION_TYPE.C2C) { //私聊时，在聊天窗口手动添加一条发的消息，群聊时，长轮询接口会返回自己发的消息
				var con = that.showMsg(msg);
				that.receiveMsgs(con)
			}
		}, function(err) {
			webim.Log.error("发送点赞消息失败:" + err.ErrorInfo);
			console.error("发送点赞消息失败:" + err.ErrorInfo);
		});
	},
	showMsg: function(msg) {
		var that = this
		var isSelfSend, fromAccount, fromAccountNick, sessType, subType;
		var ul, li, paneDiv, textDiv, nickNameSpan, contentSpan;
		fromAccount = msg.getFromAccount();
		if (!fromAccount) {
			fromAccount = '';
		}
		fromAccountNick = msg.getFromAccountNick();
		if (!fromAccountNick) {
			fromAccountNick = '未知用户';
		}
		//解析消息
		//获取会话类型，目前只支持群聊
		//webim.SESSION_TYPE.GROUP-群聊，
		//webim.SESSION_TYPE.C2C-私聊，
		sessType = msg.getSession().type();
		//获取消息子类型
		//会话类型为群聊时，子类型为：webim.GROUP_MSG_SUB_TYPE
		//会话类型为私聊时，子类型为：webim.C2C_MSG_SUB_TYPE
		subType = msg.getSubType();
		isSelfSend = msg.getIsSend(); //消息是否为自己发的
		var content = "";
		switch (subType) {
			case webim.GROUP_MSG_SUB_TYPE.COMMON: //群普通消息
				content = that.convertMsgtoHtml(msg);
				break;
			case webim.GROUP_MSG_SUB_TYPE.REDPACKET: //群红包消息
				content = "[群红包消息]" + convertMsgtoHtml(msg);
				break;
			case webim.GROUP_MSG_SUB_TYPE.LOVEMSG: //群点赞消息
				//业务自己可以增加逻辑，比如展示点赞动画效果
				content = that.convertMsgtoHtml(msg);
				//展示点赞动画
				//showLoveMsgAnimation();
				break;
			case webim.GROUP_MSG_SUB_TYPE.TIP: //群提示消息
				content = "[群提示消息]" + convertMsgtoHtml(msg);
				break;
		}
		if (fromAccount == loginInfo.identifier) {
			return {
				fromAccountNick: fromAccountNick,
				content: content,
				icon: loginInfo.icon,
				name: loginInfo.name
			}
		} else {
			return {
				fromAccountNick: fromAccountNick,
				content: content,
				member_icon: loginInfo.member_icon,
				member_name: loginInfo.member_name
			}
		}
	},
	convertMsgtoHtml: function(msg) {
		var that = this
		var html = "",
			elems, elem, type, content;
		elems = msg.getElems(); //获取消息包含的元素数组
		for (var i in elems) {
			elem = elems[i];
			type = elem.getType(); //获取元素类型
			content = elem.getContent(); //获取元素对象
			switch (type) {
				case webim.MSG_ELEMENT_TYPE.TEXT:
					html += that.convertTextMsgToHtml(content);
					break;
				case webim.MSG_ELEMENT_TYPE.FACE:
					html += convertFaceMsgToHtml(content);
					break;
				case webim.MSG_ELEMENT_TYPE.IMAGE:
					html += convertImageMsgToHtml(content);
					break;
				case webim.MSG_ELEMENT_TYPE.SOUND:
					html += convertSoundMsgToHtml(content);
					break;
				case webim.MSG_ELEMENT_TYPE.FILE:
					html += convertFileMsgToHtml(content);
					break;
				case webim.MSG_ELEMENT_TYPE.LOCATION: //暂不支持地理位置
					//html += convertLocationMsgToHtml(content);
					break;
				case webim.MSG_ELEMENT_TYPE.CUSTOM:
					html += convertCustomMsgToHtml(content);
					break;
				case webim.MSG_ELEMENT_TYPE.GROUP_TIP:
					html += convertGroupTipMsgToHtml(content);
					break;
				default:
					webim.Log.error('未知消息元素类型: elemType=' + type);
					break;
			}
		}
		return webim.Tool.formatHtml2Text(html);
	},
	convertTextMsgToHtml: function(content) {
		return content.getText();
	},
// 	setProfilePortrait: function(options, callback) {
// 		webim.setProfilePortrait(options,
// 			function(res) {
// 				webim.Log.info('修改昵称成功');
// 				callback && callback();
// 			},
// 			function() {
// 
// 			}
// 		);
// 	},
	sdkLogin: function(that, app, selToID, callback) {
		var that = this
		if (!callback) {
			callback = () => {

			}
		}
		//1v1单聊的话，一般只需要 'onConnNotify' 和 'onMsgNotify'就行了。
		//监听连接状态回调变化事件
		var onConnNotify = function(resp) {
			switch (resp.ErrorCode) {
				case webim.CONNECTION_STATUS.ON:
					webim.Log.warn('连接状态正常...');
					break;
				case webim.CONNECTION_STATUS.OFF:
					webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
					break;
				default:
					webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
					break;
			}
		};
		var onMsgNotify = function(msg) {
			console.log(msg)
			that.onBigGroupMsgNotify(msg, function(msgs) {
				that.receiveMsgs(msgs);
			})
		}
		//监听事件
		var listeners = {
			"onConnNotify": onConnNotify, //监听连接状态回调变化事件,必填			
			"onMsgNotify": onMsgNotify
		};
		//其他对象，选填
		var options = {
			'isAccessFormalEnv': true, //是否访问正式环境，默认访问正式，选填
			'isLogOn': false //是否开启控制台打印日志,默认开启，选填
		};
		//sdk登录(独立模式)
		webim.login(loginInfo, listeners, options, function(resp) {
			callback()
		}, function(err) {
			console.log("登录失败", err.ErrorInfo)
		});
	},
	onBigGroupMsgNotify:function (msgList, callback) {
		var _this = this
		for (var i = msgList.length - 1; i >= 0; i--) { //遍历消息，按照时间从后往前
			var msg = msgList[i];
			//console.warn(msg);
			webim.Log.warn('receive a new avchatroom group msg: ' + msg.getFromAccountNick());
			//显示收到的消息
			callback(_this.showMsg(msg));
			//showMsg(msg);
		}
	},
	getAvatar: function(userId,callback) {
		if (!callback) {
			callback = () => {
				console.log(1111)
			}
		}
		var that = this;
		var tag_list = ['Tag_Profile_IM_Nick', 'Tag_Profile_IM_Image']
		//用户id
		var account = userId
		var options = {
			From_Account: userId,
			To_Account: account,
			LastStandardSequence: 0,
			TagList: tag_list,
		};
		var contactList = [];
		webim.getProfilePortrait(
			options,
			function(res) {
				var UserProfileItem = res.UserProfileItem;
				var C2cNick, C2cImage;
				for (var i = 0; i < UserProfileItem.length; i++) {
					var data = UserProfileItem[i].ProfileItem;
					// 循环添加昵称和头像
					loginInfo.member_icon =  UserProfileItem[i].ProfileItem[1].Value
					loginInfo.member_name = UserProfileItem[i].ProfileItem[0].Value						
				}
				var selToID = userId.join("")
				that.getLastC2CHistoryMsgs(selToID)				
			},
			function(err) {
				console.log(err);
			}
		)
	},
	quitClick: function(callback) {
		if (loginInfo.identifier) {
			//sdk登出
			webim.logout(callback);
		} else {
			// alert('未登录');
		}
	},
	getOtherShop:function(e){
		var that = this
		var id = e.currentTarget.dataset.id
		Axios.get(app.globalData.baseUrl + 'App/Message/Message/get_store_id_by_im', {
			uid: that.uid,
			time: that.timesp,
			sign: that.Md5,
			im_id: id
		}, (res) => {
			console.log(res)
			if (res.status == 1) {
				var data = res.info
				if(res.store_id > 0){
					wx.navigateTo({
						url:'/pages/shopDetail/shopDetail?id='+data.store_id
					})
				}else{
					wx.showModal({
						content: '对方还未开通店铺',
						showCancel: false,
					})
				}						
			} else {
				that.showModal(res)
			}
		})
	},
	showModal: function(error) {
		wx.showModal({
			content: error.msg,
			showCancel: false,
		})
	},
})
